package com.mb.app.appused.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

/**
 * 用户联网操作
 * 
 * @author wo2app
 * @email wo2app@qq.com
 * @time 2015年1月31日
 * @version Vx.x.x
 * @function
 */

public class UrlClient {

	public final static int GET = 0x10000;
	public final static int POST = 0x10001;
	private CallBack callBack;
	
	public UrlClient(Context context) {
	}
	
	public void  setBackListener(CallBack callback){
		this.callBack=callback;
	}
	

	/**
	 * 设置连接
	 * 
	 * @param url
	 *            连接地址
	 * @param type
	 *            连接类型
	 * @param setKey
	 *            设置key
	 * @param setValue
	 *            设置value
	 */
	public void setClient(final String url, final int type,
			final String[] setKey, final String[] setValue) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String res=client(url, type, setKey, setValue);
					callBack.dataBack(res);
				} catch (Exception e) {
					debug("client-erro");
					callBack.erroClient();
				}

			}
		}).start();
	}
	/**
	 * 上传图片
	 * @param srcPath
	 * @param uploadUrl
	 */
	public void setUpLoadFile(final String srcPath, final String uploadUrl){
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String res=uploadFile(srcPath, uploadUrl);
					callBack.dataBack(res);
				} catch (Exception e) {
					debug("client-erro");
					callBack.erroClient();
				}

			}
		}).start();
	}

	/**
	 * 开始链接
	 * 
	 * @param url
	 * @param type
	 */
	private String client(String url, int type, String[] setKey,
			String[] setValue) {
		String res = "";
		String[] key = setKey;
		String[] value = setValue;
		switch (type) {
		case POST:
			res = postType(url, key, value);
			break;
		case GET:
			String tempUrl="";
			if(setKey!=null && setValue !=null){
			for(int i=0;i<setKey.length;i++){
					tempUrl+="/"+setKey[i]+"/"+setValue[i];
				}
			}
			res = getType(url+tempUrl);
			//Log.e("info", url+tempUrl);
			break;
		}
		return res;
	}

	/**
	 * post方式
	 * 
	 * @param url
	 */
	private String postType(String url, String[] key, String[] value) {
		String res = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			if (key != null && value != null) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (int i = 0; i < key.length; i++) {
					list.add(new BasicNameValuePair(key[i], value[i]));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
			}
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String strResult = EntityUtils.toString(
						httpResponse.getEntity(), "utf-8");
				//Log.e("info_post", strResult);
				res = strResult;
			} else {
				debug("client-post-erro-"
						+ httpResponse.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			debug("client-post-erro-client");
		}

		return res;
	}

	/**
	 * get方式
	 * 
	 * @param url
	 */
	private String getType(String url) {
		String res = "";
		try {
			HttpGet httpRequest = new HttpGet(url);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String strResult = EntityUtils.toString(
						httpResponse.getEntity(), "utf-8").trim();
				//Log.e("info", strResult);
				res = strResult;
			} else {
				debug("client-get-erro-"
						+ httpResponse.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			debug("client-get-erro-client");
		}
		return res;
	}
	
	/**
	 * 上传图片
	 * @param srcPath
	 * @param uploadUrl
	 */
	private String uploadFile(String srcPath, String uploadUrl) {
		String end = "\r\n";  
	    String twoHyphens = "--";  
	    String boundary = "******";  
		String backData="";
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();// http连接
			// 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
			// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
			httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
			// 允许输入输出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// 使用POST方法
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");// 保持一直连接
			httpURLConnection.setRequestProperty("Charset", "UTF-8");// 编码
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);// POST传递过去的编码
		//	httpURLConnection.setRequestProperty("name", userName);
			
			DataOutputStream dos = new DataOutputStream(
					httpURLConnection.getOutputStream());// 输出流
			
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
					+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
					+ "\""
					+ end
					);
			dos.writeBytes(end);
			
			FileInputStream fis = new FileInputStream(srcPath);// 文件输入流，写入到内存中
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 读取文件
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			
			dos.flush();

			InputStream is = httpURLConnection.getInputStream();// http输入，即得到返回的结果
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();
			backData=result;
			
			dos.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			// setTitle(e.getMessage());
			
		}
		return backData;
	}

	/**
	 * 打印信息
	 * 
	 * @param log
	 */
	private void debug(String log) {
		Log.e("info", log);
	}

	public interface CallBack{
		void dataBack(String data); 
		void erroClient();
	}
}
